const Service = require('egg').Service

class commentService extends Service {
  get File() {
    return this.ctx.model.File
  }
  
  // 插入下载资料
  async insert(data) {
    const _data = await new this.File(data)
    _data.save()
    return _data
  }

  // 查询下载资料
  async getList(body) {
    const pageNum = Number.parseInt(body.pageNum || 1)
    const pageSize = Number.parseInt(body.pageSize || 10)
    const titleReg = new RegExp(body.title,'ig')
    const params = {
      type: 1
    }
    if(body.title) {
      params.title = titleReg
    }
    const ret = await this.File.find(params).skip((pageNum-1)*pageSize).limit(pageSize).populate('img','link')
    const total = await this.File.countDocuments(params)
    return {
      list: ret,
      total
    }
  }


  // 删除下载资料
  async delete(id) {
    const { ctx } = this
    const _data = await this.File.findById(id)
    if(!_data) {
      ctx.throw('_id不正确！')
    }
    _data.remove()
    return {
      code: 200,
      message: '删除成功'
    }
  }

  // 修改下载资料
  async update(body) {
    const { ctx } = this
    //查找下载资料
    const _data = await this.File.findByIdAndUpdate(body.id,Object.assign(body,{updatedAt: Date.now()})) 
    if(!_data) {
      ctx.throw(422,'_id不正确！')
    }
    return {
      code: 200,
      message: '修改成功'
    }
  }
  
}

module.exports = commentService